﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Showroom.BLL;

namespace ShowroomMobile
{
    public partial class ManagerUser : AdminBasePage
    {
        private string _textSearch;
        private string TextSearch
        {
            get
            {
                return _textSearch;
            }
            set
            {
                _textSearch = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (View_Users.GetCurrentUser() != null && !View_Users.GetCurrentUser().MasterAdmin)
                {
                    Response.Redirect("~/404.aspx");
                    return;
                }
                ((AdminSite)Page.Master).SetTitlePage("User");
                gridUser.Rebind();
            }
        }

        protected void gridUser_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "DeleteAll")
            {
                //Delete all
                Showroom.BLL.Users.DeleteAllUsers();
                gridUser.CurrentPageIndex = 0;
                gridUser.Rebind();
            }
            else if (e.CommandName == "Delete")
            {
                int ID = Convert.ToInt32(e.CommandArgument);
                Showroom.BLL.Users.DeleteByID(ID);
                gridUser.CurrentPageIndex = 0;
                gridUser.Rebind();
            }
        }

        protected void gridUser_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            gridUser.CurrentPageIndex = e.NewPageIndex;
            gridUser.Rebind();
        }

        protected void gridUser_OnNeedDataSource(object sender, EventArgs e)
        {
            View_Users users = new View_Users();
            string sFilter = string.Empty;
            if (!string.IsNullOrEmpty(TextSearch))
            {
                sFilter += string.Format("{0} LIKE '%{1}%'", View_Users.ColumnNames.UserName, TextSearch);
            }
            int total = users.Search(sFilter, "[ID] desc", gridUser.CurrentPageIndex * gridUser.PageSize, gridUser.PageSize);
            gridUser.VirtualItemCount = total;
            gridUser.DataSource = users.DefaultView;
        }

        protected void btnReloadGridUser_Click(object sender, EventArgs e)
        {
            gridUser.Rebind();
        }

        protected void btnSearchUser_Click(object sender, EventArgs e)
        {
            TextSearch = txtSearchUser.Text.Trim();
            gridUser.CurrentPageIndex = 0;
            gridUser.Rebind();
        }
    }
}